<template>
  <div class="editor-view">
    <template v-if="editorStore.hasContent">
      <el-container class="editor-layout">
        <el-aside :width="editorWidth" class="editor-panel">
          <JDFEditor :on-apply-to-visualizer="handleApplyToVisualizer" />
        </el-aside>

        <el-main class="preview-panel">
          <JDFVisualizer :on-sync-to-editor="handleSyncToEditor" />
        </el-main>

        <el-divider direction="vertical" class="resize-divider" @mousedown="startResize" />
      </el-container>
    </template>

    <template v-else>
      <div class="empty-state">
        <el-empty description="请从文件管理页面加载或创建 JDF/XML 文件" />
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useEditorStore } from '@/stores/editorStore.ts'
import JDFEditor from '@/components/editor/JDFEditor.vue'
import JDFVisualizer from '@/components/flow/JDFVisualizer.vue'
import { ElMessageBox, ElMessage } from 'element-plus'

const editorStore = useEditorStore()
const editorWidth = ref('50%')
let startX = 0
let startWidth = 0

const handleSyncToEditor = async () => {
  if (!editorStore.isDirty) {
    ElMessage.info('可视化界面没有未同步的更改。');
    return;
  }
  try {
    await ElMessageBox.confirm(
      '此操作将使用可视化界面的当前状态覆盖编辑器内容，并尝试保存。确定要继续吗？',
      '同步到编辑器',
      {
        confirmButtonText: '确定同步',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    const syncSuccess: boolean = await editorStore.syncVisualChangesToEditor();
  } catch {
    ElMessage.info('同步操作已取消。');
  }
}

const handleApplyToVisualizer = async () => {
    try {
        await ElMessageBox.confirm(
            '此操作将使用编辑器当前内容（如果已更改则先保存）重新解析并覆盖可视化界面。确定要继续吗？',
            '应用到可视化',
            {
                confirmButtonText: '确定应用',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        const applySuccess: boolean = await editorStore.applyEditorChangesToVisualizer();
    } catch {
        ElMessage.info('应用操作已取消。');
    }
}

const startResize = (e: MouseEvent) => {
  startX = e.clientX
  startWidth = parseInt(editorWidth.value.replace('%','')) || 50;

  document.addEventListener('mousemove', resize)
  document.addEventListener('mouseup', stopResize)
}

const resize = (e: MouseEvent) => {
  const container = document.querySelector('.editor-layout') as HTMLElement
  if (!container) return

  const containerWidth = container.offsetWidth;
  if(containerWidth <= 0) return;

  const editorPanel = container.querySelector('.editor-panel') as HTMLElement | null;
  const currentWidthPx = editorPanel?.offsetWidth || (containerWidth * (startWidth / 100));
  const diff = e.clientX - startX;

  let newWidthPx = currentWidthPx + diff;

  const minPx = 100;
  const maxPx = containerWidth - 100;

  newWidthPx = Math.max(minPx, Math.min(maxPx, newWidthPx));

  const newWidthPercent = (newWidthPx / containerWidth) * 100;

  editorWidth.value = `${newWidthPercent}%`;
}

const stopResize = () => {
  document.removeEventListener('mousemove', resize)
  document.removeEventListener('mouseup', stopResize)
}
</script>

<style lang="scss" scoped>
.editor-view {
  height: 100%;
  overflow: hidden;

  .editor-layout {
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: row;

    .editor-panel {
      flex-basis: v-bind(editorWidth);
      flex-shrink: 0;
      flex-grow: 0;
      height: 100%;
      overflow: auto;
      position: relative;
    }

    .preview-panel {
      flex-grow: 1;
      height: 100%;
      overflow: auto;
      position: relative;
    }

    .resize-divider {
      width: 6px;
      background-color: var(--el-border-color);
      cursor: col-resize;
      z-index: 10;
      flex-shrink: 0;

      &:hover {
        background-color: var(--el-color-primary-light-3);
      }
    }
  }

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    text-align: center;
  }
}
</style>